package server;
import java.util.*;
import java.io.*;

public class Utils 
{
	public static String AppFolder = "";
	public static String ContactsFolder = "";
	
	// Searches an array list of strings for a string
	public static int SearchStringArrayList(String s, ArrayList<String> list)
	{
		for(int i=0; i<list.size(); ++i)
			if(list.get(i).equals(s))
				return i;
		
		return -1;
	}
		
	// Reads a text file and loads its lines into an array list of strings
	public static ArrayList<String> loadStringsFile(String filename)
	{
		ArrayList<String> result = new ArrayList<String>();
		String line = null;
		
		if(new File(filename).exists() && new File(filename).canRead())
		{
			try
			{			
				BufferedReader br = new BufferedReader(new FileReader(filename));
				
				do
				{
					line = br.readLine();
					
					if(line != null)
						result.add(line);
				}
				while(line != null);
				
				br.close();
				
			} // TRY
			catch(Exception e)
			{
				System.out.println("In Utils::loadStringsFile():");
				e.printStackTrace();
				System.exit(-1);
			} // CATCH
		} // IF
		
		return result;
	}
	
	// Same as above but assumes the file contains only one line
	public static String loadStringFile(String filename)
	{
		ArrayList<String> result = Utils.loadStringsFile(filename);
		
		if(result.size() == 0)
			return "";
		else
			return result.get(0);
	}
	
	// saves an array list of strings to a file
	public static void saveStringsFile(ArrayList<String> strings, String filename)
	{
		try
		{
			BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
			
			for(int i=0; i<strings.size(); ++i)
				bw.write(strings.get(i)+"\n");
			
			bw.close();
		} // TRY
		catch (Exception e)
		{
			System.out.println("In Utils::saveStringsFile():");
			e.printStackTrace();
			System.exit(-1);			
		} // CATCH
	}
	
	// same as above but saves only one string
	public static void saveStringFile(String string, String filename)
	{
		ArrayList<String> strings = new ArrayList<String>();
		strings.add(string);
		saveStringsFile(strings, filename);
	}
}
